<?php
/**
 * Created by PhpStorm.
 * User: dayu
 * Date: 2019/12/24
 * Time: 14:45
 */

namespace app\api\controller;


use think\Controller;
use data\service\ActivityGoods;
use app\Validate\DiscountListValidate;
use data\service\Pay\WeiXinPay;
use data\service\WxPay;
use app\Validate\WxValidate;
use think\Exception;
use data\model\FamilyCardOrderModel;

class Wx extends BaseController
{

    /**
     * 设置微信支付参数
     *
     * @param unknown $body 订单描述
     * @param unknown $detail 订单详情
     * @param unknown $total_fee 订单金额
     * @param unknown $orderNumber 订单编号
     * @param unknown $red_url 异步回调域名
     * @param unknown $trade_type 交易类型JSAPI、NATIVE、APP
     * @param unknown $openid 支付人openid（jsapi支付必填）
     * @param unknown $product_id 商品id(扫码支付必填)
     * @return unknown oH04R5V582uDY9PRZixoqBgpjci8
     */
    public function JsApiPay(WxValidate $wxValidate)
    {
        $wx = new WxPay();
        $Body = $wxValidate->request->post('Body');
        $Out_trade_no = $wxValidate->request->post('Out_trade_no');
        $Attach = $wxValidate->request->post('type');
        $Goods_tag = $wxValidate->request->post('Goods_tag', '');
        $FamilyCardOrderModel= new FamilyCardOrderModel();
        $Total_fee = $FamilyCardOrderModel->where('order_no',$Out_trade_no)->value('price');
        if(empty($Total_fee)){
            return return_json_data('订单号错误',500);
        }
        $data = $wx->JsApiPay($Body, $Out_trade_no, (int)($Total_fee*100), $this->openid, $Attach, $Goods_tag);
        if (isset($data['error'])) {
            return return_json_data($data['error'], 500);
        }
        return return_json_data(['data' => $data], 200);
    }


    public function Wxlogin()
    {
        $code = request()->get('code');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . config('wxPay')['APPID'] . "&secret=" . config('wxPay')['SECRET'] . "&js_code=" . $code . "&grant_type=authorization_code";
        $res = json_decode(http($url), true);
        if (isset($res['errcode'])) return return_json_data($res['errmsg'], 500);

    }


    /**
     * 微信回调数据处理
     * @return array
     * @throws \WxPayException
     */
    public function NotifyUrl()
    {

        $wx = new WxPay();
        $xml = file_get_contents("php://input");
//        $xml = "<xml><appid><![CDATA[wx7d0a3a3aab7e3c0b]]></appid>
//                <attach><![CDATA[2]]></attach>
//                <bank_type><![CDATA[ICBC_DEBIT]]></bank_type>
//                <cash_fee><![CDATA[1]]></cash_fee>
//                <fee_type><![CDATA[CNY]]></fee_type>
//                <is_subscribe><![CDATA[N]]></is_subscribe>
//                <mch_id><![CDATA[1535221551]]></mch_id>
//                <nonce_str><![CDATA[w86d388bqsxd5vulfln0b3r71aur09yu]]></nonce_str>
//                <openid><![CDATA[oH04R5V582uDY9PRZixoqBgpjci8]]></openid>
//                <out_trade_no><![CDATA[202001165410249559]]></out_trade_no>
//                <result_code><![CDATA[SUCCESS]]></result_code>
//                <return_code><![CDATA[SUCCESS]]></return_code>
//                <sign><![CDATA[52148D2589781C563F9AC48B9BA61D6A]]></sign>
//                <time_end><![CDATA[20200116155617]]></time_end>
//                <total_fee>1</total_fee>
//                <trade_type><![CDATA[JSAPI]]></trade_type>
//                <transaction_id><![CDATA[4200000495202001165943116053]]></transaction_id>
//                </xml>";
        $array = xmlToArray($xml);
        $orderquery = $wx->orderquery($array['out_trade_no']);
        if ($orderquery['return_code'] == "SUCCESS" && $orderquery['return_msg'] == "OK") {
            if ($array['attach'] == 2) {
                $service = new \data\service\Family();
                $data['order_no'] = $array['out_trade_no'];
                $boole = $service->purchaseFamilyCard($data);
                if ($boole['status'] === false) {
                    $refund = $wx->refund($array['out_trade_no'], $array['total_fee'], $array['total_fee']);
                    if (isset($refund['error'])) {
                        file_put_contents("refundMoneyList.txt", $array['out_trade_no'] . PHP_EOL, FILE_APPEND);
                    }
                }
                return ["return_code" => "SUCCESS"];
            } else if ($array['attach'] == 1) {

            }
        }
    }

}